// Copyright 2009 sbva project
//
// This file is part of sbva,
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlecode.sbva.example;

import com.googlecode.sbva.DefaultStrutsBeanValidationAdapter;
import com.googlecode.sbva.example.businessobjects.Address;
import com.googlecode.sbva.example.businessobjects.Person;
import com.googlecode.sbva.example.businessobjects.SocialSecurityNumber;
import com.googlecode.sbva.StrutsBeanValidationAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class UserForm extends ActionForm {

   private static Log log = LogFactory.getLog(UserForm.class);
   private static DefaultStrutsBeanValidationAdapter beanValidationToStrutsConverter = new DefaultStrutsBeanValidationAdapter() {

      public String mapPropertyToFormInput(String propertyName) {
         String newPropertyName = propertyName;

         if ("person.ssn".equals(propertyName)) {
            newPropertyName = "person.ssn.area";
         }

         return newPropertyName;
      }
   };

   static {

      beanValidationToStrutsConverter.setReturnNull(true);
   }

   @Valid
   private Person person = new Person();

   public Person getPerson() {
      return this.person;
   }

   public void setPerson(Person person) {
      this.person = person;
   }

   public UserForm() {
      if (log.isDebugEnabled()) {
         log.debug("Instantiating " + getClass().getName() + ".");
      }
      this.person.setSsn(new SocialSecurityNumber());
      this.person.setAddress(new Address());
   }

   @Override
   public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
      if (log.isDebugEnabled()) {
         log.debug("Starting " + getClass().getName() + " validation..");
      }
      return beanValidationToStrutsConverter.beanValidationErrorsToActionErrors(this, request);
   }

   public void setBeanValidationToStrutsConverter(StrutsBeanValidationAdapter beanValidationToStrutsConverter) {
      beanValidationToStrutsConverter = beanValidationToStrutsConverter;
   }
}
